package com.xjnt.mnui.controller;


import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.jfinal.aop.Before;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.xjnt.frameworks.annotation.AutoInject;
import com.xjnt.frameworks.annotation.Router;
import com.xjnt.frameworks.core.CRUDController;
import com.xjnt.frameworks.exception.BusinessException;
import com.xjnt.frameworks.web.message.RetDataMsg;
import com.xjnt.frameworks.web.message.RetMsg;
import com.xjnt.mnui.entity.Subject;
import com.xjnt.mnui.entity.SubjectAssets;
import com.xjnt.mnui.entity.SubjectTemplate;
import com.xjnt.mnui.service.SubjectAssetsService;
import com.xjnt.mnui.service.SubjectService;
import com.xjnt.mnui.service.SubjectTemplateService;

@Router(name="/mnui/sub/sub", view="/mnui/subject")
public class SubjectController extends CRUDController<Subject, SubjectService> {

	@AutoInject
	private SubjectService subjectService;
	@AutoInject
	private SubjectTemplateService subjectTemplateService;
	@AutoInject
	private SubjectAssetsService subjectAssetsService;
	@Override
	protected String getBizName() {
		return "专题";
	}

	@Override
	protected Class<Subject> getClazz() {
		return Subject.class;
	}

	@Override
	protected SubjectService getService() {
		return subjectService;
	}
	/**
	 * @Override add方法，增加页面选择模板，选择资产的select
	 */
	@Override
	public void add() {
		keepPara();
		addBefore();
		setAttr(getService().getModel().getModelName(), getService().getModel());
		//页面选择模板
		setAttr("templateList", subjectTemplateService.findTemplateList());
		render("add.html");
	}
	/**
	 * @Override edit方法，增加页面选择模板，选择资产的select
	 */
	@Override
	public void edit() {
		keepPara();
		Subject model = getService().findById(getPara("id"));
		editBefore(model);
		setAttr(model.getModelName(), model);
		//页面选择模板
		setAttr("templateList", subjectTemplateService.findTemplateList());
		render("edit.html");
	}

	/**
	 * 保存方法
	 */
	@Override
	public void doSave() {
		RetMsg retMsg = new RetMsg();
		String name = getPara("name");
		String pages = getPara("pages");
		String templateId = getPara("templateId");
		String remark = getPara("remark");
		
		try {
			//subject操作
			Subject subject = new Subject();
			subject.set("name", name);
			subject.set("pages", pages);
			subject.set("template_uuid", templateId);
			subject.set("remark", remark);
			subject.set("create_time", new Date());
			subject.set("type", 0);
			boolean flag = getService().save(subject);
			if (flag) {
				retMsg.pushOk("保存成功");
			} else {
				retMsg.pushError("保存失败");
			}
			renderJson(retMsg);
		} catch (Exception e) {
			throw new BusinessException("保存" + getBizName(), "发生异常：", e);
		}
	}
	/**
	 * 更新方法
	 */
	@Override
	public void doUpdate(){
		RetMsg retMsg = new RetMsg();
		String uuid = getPara("uuid");
		String name = getPara("name");
		String pages = getPara("pages");
		String templateId = getPara("templateId");
		String remark = getPara("remark");
		try {
			//subject操作
			Subject subject = new Subject();
			subject.set("uuid", uuid);
			subject.set("name", name);
			subject.set("pages", pages);
			subject.set("template_uuid", templateId);
			subject.set("remark", remark);
			subject.set("type", 0);
			boolean flag = getService().update(subject);
			if (flag) {
				retMsg.pushOk("保存成功");
			} else {
				retMsg.pushError("保存失败");
			}
			renderJson(retMsg);
		} catch (Exception e) {
			throw new BusinessException("保存" + getBizName(), "发生异常：", e);
		}
	}
	/**
	 * 数据删除
	 * 当删除专题时，需要将专题所关联的资产的sub_uuid，sub_name清空
	 */
	@Before(Tx.class)
	@Override
	public void deletes() {
		RetMsg retMsg = new RetMsg();
		try {
			String idStr = getPara("ids");
			Object[] ids = idStr.split(",");
			//循环将关联的资产的sub_uuid，sub_name清空
			for (Object subUuid : ids) {
				List<SubjectAssets> l = subjectAssetsService.getListBySubId(subUuid);
				for (SubjectAssets subjectAssets : l) {
					SubjectAssets a = subjectAssetsService.findById(subjectAssets.get("uuid"));
					a.set("sub_uuid", null);
					a.set("sub_name", null);
					subjectAssetsService.update(a);
				}
			}

			boolean flag = getService().deleteByIds(ids);
			if (flag) {
				retMsg.pushOk("批量删除成功");
			} else {
				retMsg.pushError("批量删除失败");
			}
			renderJson(retMsg);
		} catch (Exception e) {
			throw new BusinessException("批量删除" + getBizName(), "发生异常：", e);
		}
	}
	/**
	 * 启用/停用 ajax方法
	 */
	public void enableAJax(){
		RetMsg retMsg = new RetMsg();
		String able = getPara("type");//0:启用,1:停用
		String idStr = getPara("ids");
		Object[] ids = idStr.split(",");
		try {
			for (Object id : ids) {
				Subject model = getService().findById(id);
				if("0".equals(able)){
					model.set("type", "0");
				}
				if("1".equals(able)){
					model.set("type", "1");
				}
				boolean flag = getService().update(model);
				if (flag) {
					retMsg.pushOk("操作成功");
				} else {
					retMsg.pushError("操作失败");
				}
			}
			renderJson(retMsg);
		} catch (Exception e) {
			throw new BusinessException("保存" + getBizName(), "发生异常：", e);
		}
	}
	/**
	 * 生成专题静态页面。
	 */
	@Before(Tx.class)
	public void createStaticHtml(){
		RetMsg retMsg = new RetMsg();
		keepPara();
		String idStr = getPara("ids");
		Object[] ids = idStr.split(",");
		for (Object uuid : ids) {
			//获得subject实体
			Subject model = getService().findById(uuid);
			//通过subject的template_id获取模板实体
			SubjectTemplate template = subjectTemplateService.findById(model.get("template_uuid"));
			//通过sub_uuid获得资产List<SubjectAssets>
			List<SubjectAssets> assetsList = subjectAssetsService.getListBySubId(uuid);
			
			//对static页面需要的json数据进行生成 begin
			Map<Object,Object> map = new HashMap<Object,Object>();
			map.put("name", "影片");
			map.put("pages", model.get("pages"));
			int size = assetsList.size();
			int pages = model.get("pages");
			int pageSize = size%pages==0?size/pages:size/pages+1;//计算pageSize
			map.put("pageSize",pageSize);
			String bgUrl = "";
			bgUrl = template.get("bg_url");
			map.put("bgImg", bgUrl);//背景图片url
			map.put("subject_uuid", model.get("uuid"));//专题id
			map.put("subject_code", model.get("subject_code"));//专题code
			List<Map<Object, Object>> l = new ArrayList<>();
			for (SubjectAssets subjectAssets : assetsList) {
				Map<Object,Object> map1 = new HashMap<Object,Object>();
				map1.put("img", subjectAssets.get("img_url"));
				map1.put("focusImg", subjectAssets.get("focus_img_url"));
				map1.put("url", subjectAssets.get("url"));
				map1.put("create_time", subjectAssets.get("create_time"));
				map1.put("update_time", subjectAssets.get("update_time"));
				l.add(map1);
			}
			map.put("subList", JSON.parseArray(JsonKit.toJson(l)));
			RetDataMsg dataMsg = new RetDataMsg(true);//静态页面中需要的数据
			dataMsg.setRows(JSON.toJSONString(map));
			//对static页面需要的json数据进行生成 end
			//生成静态html begin
			String path = getRequest().getServletContext().getRealPath("/static/"); 
			String name = model.get("subject_code").toString();//使用专题code作为文件名称
			String fileName = name + ".html";//按照以下格式生成html文件：专题主键.html
			String fileContent = template.get("code");
			String c = fileContent.replaceAll("###menuListData###", dataMsg.getRows().toString());//对模板文件中的数据进行替换
			try {
				createNewFile(path+"/", fileName, c);//生成页面
			} catch (IOException e) {
				throw new BusinessException("生成静态页面" + getBizName(), "发生异常：", e);
			}
			//生成静态html end
			String strBackUrl = "http://" + getRequest().getServerName() //服务器地址
			        + ":" 
			        + getRequest().getServerPort()           //端口号
			        + getRequest().getContextPath()      //项目名称
			        + "/mnui/external/sub/render/render?code="+model.get("subject_code");
			model.set("url", strBackUrl);
			subjectService.update(model);
		}
		retMsg.pushOk("操作成功");
		renderJson(retMsg);
	}
	/**
	 * 生成html文件方法
	 * @param path 文件目录 
	 * @param fileName 文件名称
	 * @param fileContent 写入内容
	 * @throws IOException 
	 */
	public static String createNewFile(String path,String fileName, String fileContent) throws IOException {
		String filepath = path;
		// 创建File对象，参数为String类型，表示目录名
		File FileDir = new File(filepath);
		//文件路径不存在
		if(!FileDir.isDirectory()){
			FileDir.mkdirs();
		}
		// 判断文件是否存在，如果不存在则调用createNewFile()方法创建新目录，否则跳至异常处理代码
		File myFile = new File(filepath + fileName); 
		if (!myFile.exists()) {
			myFile.createNewFile();
		}
		else {// 如果存在则删除原有文件，重新创建
			myFile.delete();
			myFile.createNewFile();
		}
		// 下面把数据写入创建的文件，首先新建文件名为参数创建FileWriter对象
		FileWriter resultFile = new FileWriter(myFile);
		// 把该对象包装进PrinterWriter对象
		PrintWriter myNewFile = new PrintWriter(resultFile);
		// 再通过PrinterWriter对象的println()方法把字符串数据写入新建文件
		myNewFile.println(fileContent);
		resultFile.close(); // 关闭文件写入流
		return myFile.getAbsolutePath();
	}
}
